require "Net/send_Msg"
require "Net/TitleHandler"
require "Net/skillHandler"
require "Net/HeroSoulHandler"
require "Net/HeroPotentialHandler"
require "Net/mythicDungeonsProHandler"
require "proto/player/message/ReqSettleMessage"
require "proto/player/message/ReqQuickMessage"
require "proto/player/message/ReqChangeLbsMessage"
require "proto/player/message/ReqUnlockModuleListMessage"
require "proto/player/message/ReqUnlockModuleMessage"
require "proto/server/message/ReqCloseFunctionDataMessage"

require "RedDots/RedDotsManager"
RedDotsManager.init()

playerHandler = playerHandler or {};
G.serverData = G.serverData or {};

local SEND_FUNC_OPEN_ID = {
    404,--专武
    1090,--宠物牧场
    304, --远征开启
}
-- 主角信息
function playerHandler.receivePlayerInfo(msg)
    G.serverData["roleInfo"] = G.serverData["roleInfo"] or {};
    chatHandler.ReqChatServiceInfo()
    --show信息
    G.serverData["roleInfo"].show = {};
    if msg.show ~= nil then
        logicMgr.HeroManager.InitRoleInfo(msg.show)

        G.serverData["roleInfo"].show.playerId = tostring(msg.show.playerId);
        G.serverData["roleInfo"].show.leaderModelId = 1--msg.show.modelId() --弃用   新版没有主角英雄的概念了,为了防止报错这里临时写死，后期需要干掉相关代码
        G.serverData["roleInfo"].show.level = msg.show.level;
        G.serverData["roleInfo"].show.name = msg.show.name;
        G.serverData["roleInfo"].show.createTime = msg.show.createTime;
        G.serverData["roleInfo"].show.headID = toNumber(msg.show.pic)
        G.serverData["roleInfo"].show.picFrame = toNumber(msg.show.picFrame)
        G.serverData["roleInfo"].show.formation = msg.show.formation;
        G.serverData["roleInfo"].show.unionId = msg.show.unionId;

        logicMgr.FriendManager.SetBlackList(msg.blackPlayers)
        --G.serverData["roleInfo"].show["exp"] = exp;

        logicMgr.HeroManager.SetRoleHeadID(toNumber(logicMgr.SkinManager.getHeroModelIdBySkinId(msg.show.pic)))
        --logicMgr.HeroManager.setMySelfPartnerId(logicMgr.HeroManager.GetRoleInfo().leaderModelId,logicMgr.HeroManager.GetRoleInfo().playerId);
        logicMgr.HeroManager.setMySelfPartnerId() -- 为了防止报错 兼容写法
		logicMgr.HeroManager.setHeroLevel(G.serverData["roleInfo"].show.playerId,logicMgr.HeroManager.GetRoleInfo().level);
        logicMgr.HeroManager.setHeroName(G.serverData["roleInfo"].show.playerId,logicMgr.HeroManager.GetRoleInfo().name);
        logicMgr.HeroManager.setHeroStar(G.serverData["roleInfo"].show.playerId,0);
        logicMgr.HeroManager.RefreshHeroAdd();
        logicMgr.HeroManager.changePic = msg.changePic or 1
		--logicMgr.HeroManager.setHeroExp(G.serverData["roleInfo"].show.playerId, logicMgr.HeroManager.GetRoleInfo()["exp"]);
        --logicMgr.HeroManager.updateHeroBaseAttr(G.serverData["roleInfo"].show.playerId);
        logicMgr.MapManager.setMapId(msg.show.dungeonId);
        logicMgr.MapManager.SetBattleBeforeMapId(msg.show.dungeonId)
        logicMgr.HeroManager.SetCityShowFirstRankPlayer(msg.cityShowInfo)
        logicMgr.GuideMgr.SetSoftGuideMapId(msg.show.dungeonId)
        logicMgr.VipManager.setVipLevel(msg.show.vipLv)
        logicMgr.CostManager.setPlayerRechargeSum(msg.show.rechargeSum)
        logicMgr.HeroManager.setOnlineTime(msg.todayOnlineTime);
        InputMgr.InitCheck();
    end

    --货币
    if msg.currencyAttributes ~= nil then
        for i=1, #msg.currencyAttributes do
            logicMgr.ItemManager.setCurrencyCount(msg.currencyAttributes[i].type,tonumber(msg.currencyAttributes[i].value:tostring()),-1,"");
        end
    end
    G.serverData["roleInfo"].show["nextexp"] = G.dataTable["t_characterexp"][MakeTopLevelId(msg.show.level)].f_CharacterExp;
    AppConst.ServerId = tonumber(msg.serverId);

    -- 看板娘
    HeroManager.setShowFemaleRole(msg.showFemaleRole)
    HeroManager.setShowTravelFemaleRole(msg.showTravelFemaleRole)

    -- 主城背景
    G.serverData['cityBg'] = msg.cityBackground
    --战报上传接口
    G.serverData['webPort'] = msg.webPort

    --登录聊天服务器
    if IsWindowEditor() then
        --WebSocketMgr.GetInstance():Close()
        --WebSocketMgr.GetInstance():loginChat(logicMgr.LoginManager.GetHttpChatUrl()..logicMgr.HeroManager.GetRoleInfo().playerId);
    end
    --SDK
    local roleinfo = logicMgr.HeroManager.GetRoleInfo().playerId..","..logicMgr.HeroManager.GetRoleInfo().name..",".."区服名"..","..msg.show.level;
    if AppConst.isBussiness == 0 then
        LoginSDK.GetInstance():startGameSDK(roleinfo);
    end



    --创角时间      [这里应该是创建账号时间吧？？ --by ZhengFeng]
    --if msg.createPlayerTime ~= nil then
    --    logicMgr.ShopManager.AddCreateCharactorTime(msg.createPlayerTime);
    --end

    TAManager.Login()
    local _createTimeStr = TimeFormateByMs(tonumber(G.serverData["roleInfo"].show.createTime) * 1000)
    TAManager.UserSet("role_create_time",_createTimeStr)
    TAManager.UserSet("register_time",_createTimeStr)
    TAManager.UserSet("role_create_time_test",_createTimeStr..":00")
    --printError("role_create_time ----------".._createTimeStr.."        "..G.serverData["roleInfo"].show.createTime)
    local _currentTimeStr = TimeFormateByMs(HelperFunc.GetServerTime(false))
    TAManager.UserSet("final_login_time",_currentTimeStr)
    TAManager.UserSet("final_login_time_test",_currentTimeStr..":00")
    TAManager.UserSet("last_login_time",_currentTimeStr)
    --printError("final_login_time ----------".._currentTimeStr.."        "..HelperFunc.GetServerTime(false))

    TAManager.UserSet("role_id",tostring(G.serverData["roleInfo"].show.playerId))
    TAManager.UserSet("role_name",G.serverData["roleInfo"].show.name)
    TAManager.UserSet("role_level",tonumber(G.serverData["roleInfo"].show.level))
    TAManager.UserSet("server_id", AppConst.ServerId)
    TAManager.UserSet("channel", tostring(Config.SDK_Channel))
    TAManager.UserSet("sub_channel", tostring(Config.SDK_SubChannel))

    TAManager.UserSet("device_id", SystemInfo.deviceUniqueIdentifier)

    TAManager.UserSet("new_player", LoginManager.exist_role)
    TAManager.TrackByDictionary("is_new_player", {is_new = LoginManager.exist_role})
    if logicMgr.LoginManager.user_id then
        TAManager.UserSet("u_id", logicMgr.LoginManager.user_id)
    end

    TAManager.UserAdd("total_login", 1)
    TAManager.SetSeverCountProperty()

    TAManager.TrackByDictionary("receive_role_info", {create_role_time = _createTimeStr})
    LoginSDK.GetInstance():SubmitExtraData(3, tostring(msg.show.playerId), logicMgr.HeroManager.GetRoleInfo().name, tostring(msg.show.level), AppConst.ServerId);

        --角色初始技能
    --playerHandler.updateRoleSkill();

    --mapMgr:FreshRoleData(getJsonStr(logicMgr.HeroManager.GetRoleInfo()));

    --roleInfoHandler.startCalculateExp();
    --RoleAttributeModel.updateLevelAttribute();
    --FireEvent(Config.EventType.Fresh_UILock);

    --请求玩家数据信息
    --roleInfoHandler.sendreqRoleInfo();

    RedDotsManager.addHandler();
    --将魂
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroSoul,false) then
        HeroSoulHandler.ReqHeroSoulDirListInfo()
    end
    -- 集市信息
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Cost,false) then
        -- 用户分层
        costHandler.reqPayGrade()
        costHandler.reqGetMarketInfo()
    end
    -- VIP信息
    if logicMgr.VipManager.getVipLevel() >= 0 then
        vipHandler.reqGetVipInfo()
    end
    -- 贵族特权
    --vipHandler.reqGetPrivilegeInfo()
    --请求勋章信息
    --if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Title,false) then
        TitleHandler.SendTitleInfo();
    --end
    --请求援助技能
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.SupSkill,false) then
        skillHandler.SendReqAssistantSkill();
    end
    --时间宝箱TimeBoxAll
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.TimeBoxAll,false) then
        TimeBoxHandler.ReqTimeBoxInfoUpdate()
    end
    --好友礼物Friend
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Friend,false) then
        friendHandler.ReqFriendData()
        friendHandler.ReqAllFriendGiftList()
    end
    --羁绊Restrain
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Restrain,false) then
        partnerHandler.sendFetterAwaraList()
    end
    --远征
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.expedition,false) then
        ExpeditionHandler.ReqSynExpedition(true)
    end
    if CompareOriginVersion("1.4.2.0001") then
        --获取定位后移 LBSManager.StartLocation
    else
        --定位--------------------------------------------------------------------------------------------------
        playerHandler.ReqChangeLbsMessage(logicMgr.LBSManager.GetLocationName())
    end


    --任务Task
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Task,false) then
        taskInfoHandler.sendReqTaskMessage()
    end
    --开放列表
    playerHandler.ReqUnlockModuleList()
    --开放列表Activity
    --七天登陆Sevenday
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Activity,false) then
        ActivityHandler.sendReqSevenDayMessage()
        newPlayerActiveHandler.ReqShareActivityInfo()
        ActivityHandler.sendReqActivityInfoListMessage()
    end
    --公告牌红点用OperationNotice
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.OperationNotice,false) then
        NoticeHandler.ReqRedDots(true,false)
    end

    -- 排位战RankBattle
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.RankBattle,false) then
        RankBattleHandler.ReqRankBattlePlayerInfo()
    end
    --好友战FriendBattle
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.FriendBattle,false) then
        --FriendBattleHandler.ReqTimeInfo()
    end
    --竞技场
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Arena,false) then
        arenaHandler.sendReqArenaInfo();
    end
    --旋云远征深渊4
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.LongJourneyHell,false) then
        longJourneyHellHandler.reqLongJourneyHellInfo();
    end
    --高阶竞技场
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.CrossTeamArena,false) then
        crossTeamArenaHandler.sendReqHighArenaInfo();
    end
    --剧情模式数据
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.StoryModelReward) then
        dungeonHandler.ReqHardDungeonInfoHandler()
    end
    --InvasionHandler.ReqInitTeamBoss(0)
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.InvasionBattle) and logicMgr.InvasionManager.IsOpen() then
        InvasionHandler.ReqOpenHighReward(0) --0，请求信息  1，开启高收益
    end
    --服务端锁定信息-----------------------------------------------------------------------------
    playerHandler.ReqCloseFunctionDataMessage()
    --公会信息
    if msg.show.unionId and msg.show.unionId > 0 then
        unionHandler.reqUnionInfoMessage();
        --
        --unionHandler.reqUnionBossInfo(msg.show.unionId)
        --公会战
        --unionWarHandler.reqUnionWarInfo(0)
        --unionWarPlusHandler.reqGuildBattleInfo(0, EnumConst.GuildBattlePlusType.Territory)
        --unionWarPlusHandler.reqGuildBattleInfo(0, EnumConst.GuildBattlePlusType.Championship)
        --公会心愿
        --unionWishtHandler.reqUnionWishInfo()
        --军团帮助
        --plunderHandler.SendGetUnionHelpInfo()
        logicMgr.GuildManager.Track_GuildSubFuncData(msg.show.unionId, 0);
        ----军团科技
        --if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Guild,false) then
        --    unionHandler.sendReqReqUnionTechInfo()
        --end
    end
    --暗巷信息
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.DarkStreet,false) then
        DarkStreetHandler.ReqDarkInfo()
        DarkStreetHandler.ReqDarkAlleyFormations()
    end
    --返利信息
    costHandler.ReqVoucherData();
    --分享次数
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Bag,false) then
        logicMgr.ShareManager.Req_shareTimes()
    end

    logicMgr.LoginManager.RefreshGameTime()
    -- 阵容推荐
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.BattleRecommend,false) then
        partnerHandler.ReqFormationRecInfo()
    end
    -- 上届浮岛争霸结果
    --unionWarPlusHandler.reqLastRecord(-1, EnumConst.GuildBattlePlusLastRecordType.Championship);
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.TeamEditor,false) then
        logicMgr.FormationManager.req_FormationList()
    end
    -- 宠物
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Pet,false) then
        PetHandler.ReqAllPet();
    end
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.PetPartAttr,false) then
        PetHandler.ReqPartListInfo()
        skillHandler.SendReqPetSkillList()
    end
    -- 邮件
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Mail,false) then
        emailHandler.ReqAllMail()
    end
    -- 永劫之境
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Mythic,false) then
        mythicDungeonsHandler.ReqInstanceInfo();
        mythicDungeonsProHandler.ReqInstanceInfo();
    end
    -- 爬塔
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Tower,false) then
        towerHandler.sendGetTowerInfo()
    end

    -- 家园
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroManor,false) then
        HeroManorHandler.sendReqManorInfoMessage(1);
    end

    -- 新加协议需判断解锁条件，initUnlockFuncList 这个里面也要补充
    logicMgr.UnlockFuncManager.initUnlockFuncList(); -- 初始化待解锁功能

    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.OperationNotice, false) then
        logicMgr.BillboardMgr.OnLoginReq()
    end
    --潜能
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Potential,false) then
        HeroPotentialHandler.ReqPotentialInfo()
    end
end

function playerHandler.receivePlayerLevelUp(msg)
    --log("playerHandler.receivePlayerLevelUp");
    --dataTable.PrintTable(msg);
    if msg.state == 0 then
        logicMgr.HeroManager.SetLastPlayerLevel(logicMgr.HeroManager.GetRoleLevel());
        G.serverData["roleInfo"].show.level = msg.level;
        TAManager.UserSet("role_level",tonumber(G.serverData["roleInfo"].show.level))
        local levelExpCg = G.dataTable["t_characterexp"][MakeTopLevelId(msg.level)];
        logicMgr.HeroManager.setHeroLevel(logicMgr.HeroManager.GetRoleId(),msg.level);
        if levelExpCg~=nil then
            G.serverData["roleInfo"].show["nextexp"] = levelExpCg.f_CharacterExp;
        end
        FireEvent(Config.EventType.Fresh_Level,2);
        playerHandler.CheckSendFuncUnlock()
        LoginSDK.GetInstance():SubmitExtraData(4, tostring(logicMgr.HeroManager.GetRoleId()), tostring(logicMgr.HeroManager.GetRoleName()), tostring(msg.level), AppConst.ServerId);
        -- --玩家等级提升音效
        -- AudioManager.Play(2014)
    end
end

function playerHandler.receiveSettleReward(msg)
    --log("playerHandler.receiveSettleReward");
    --dataTable.PrintTable(msg);
    if msg.state == 0 then
        local settleTime = msg.settleTime - logicMgr.HeroManager.getSettleTime()
        local plunders = msg.plunders
        logicMgr.HeroManager.setSettleTime(msg.settleTime);
        local data = {time=settleTime,items=msg.items, plunders= plunders};
        FireEvent(Config.EventType.SettleReward,data);

        -- 领取挂机奖励后
        local _rewardDic = {}
        _rewardDic.setting_time = tostring(settleTime)
        TAManager.TrackByDictionary("stage_reward",_rewardDic)

        local sec = HelperFunc.GetServerTime(true)
        -- local next = logicMgr.PushManager.caculateHookMaxDate()
        -- logError("next time:" .. next)
        logicMgr.PushManager.Req_AddPush(EnumConst.PushType.SettleReward)

        -- iOS Widget: 更新挂机时间
        if CompareOriginVersion("1.4.2.0001") then
            local tick = logicMgr.HeroManager.getSettleTime()
            local maxHangTime = logicMgr.HeroManager.getSettleingMaxTime()
            LoginSDK.GetInstance():SetWidgetGetRewardTick(tick, maxHangTime)
        end
    end
end

function playerHandler.receiveQuickReward(msg)
    --log("playerHandler.receiveQuickReward");
    --dataTable.PrintTable(msg);
    if msg.state == 0 then
        logicMgr.HeroManager.setQuickTimes(msg.quickTimes);
        local data = {items=msg.items};
        FireEvent(Config.EventType.QuickBattle,data)

        local _rewardDic = {}
        _rewardDic.sweep_times = tonumber(msg.quickTimes)
        --_rewardDic.sweep_cost = G.dataTable["t_sweep"][tostring(_rewardDic.sweep_times + 1)]["f_SweepCost"]
        TAManager.TrackByDictionary("stage_sweep_reward",_rewardDic)
    end

end

function playerHandler.receivePlayerCurrencyAttributesChange(msg)
    --log("playerHandler.receivePlayerCurrencyAttributesChange");
    --dataTable.PrintTable(msg);

    logicMgr.ItemManager.setCurrencyCount(msg.attributes.type, tonumber(msg.attributes.value:tostring()),msg.sourceCode,msg.params);
    FireEvent(Config.EventType.Fresh_Currency);
end

--玩家挂机
function playerHandler.sendSettleMessage()
    local req = ReqSettleMessage.New();
    sendReqMessage(req);
end

--快速战斗
function playerHandler.sendQuickBattle()
    local req = ReqQuickMessage.New();
    sendReqMessage(req);
end

--- 发送调戏其他玩家请求，服务器不需要响应
--- @param otherPlayerId string 他人玩家id
function playerHandler.sendPickOtherPlayerMessage(otherPlayerId)
    local req = ReqPickOtherPlayerMessage.New()
    req.otherPlayerId = otherPlayerId
    sendReqMessage(req)
end
function playerHandler.ReqChangeLbsMessage(location)
    local req = ReqChangeLbsMessage.New()
    req.lbs = location
    sendReqMessage(req)
end
function playerHandler.IsFuncUnlock(id)
    if not G.serverData["FuncUnlock"] then
        return false
    end
    return G.serverData["FuncUnlock"][id]
end
function playerHandler.CheckSendFuncUnlock()
    for k,v in pairs(SEND_FUNC_OPEN_ID) do
        if logicMgr.FuncOpenManager.isOpen(v) then
            if not playerHandler.IsFuncUnlock(v) then
                playerHandler.ReqUnlockModule(v)
            end
        end
    end
end
--请求功能解锁
function playerHandler.ReqUnlockModule(id)
    local m = ReqUnlockModuleMessage.New()
    m.moduleId = id
    sendReqMessage(m)
end
--请求功能解锁列表
function playerHandler.ReqUnlockModuleList()
    local m = ReqUnlockModuleListMessage.New()
    sendReqMessage(m)
end
function playerHandler.ResUnlockModuleHandle(msg)
    if msg.state ~= 0 then return end
    if not G.serverData["FuncUnlock"] then
        return
    end
    G.serverData["FuncUnlock"][msg.moduleId] = true
    FireEvent(Config.EventType.Refresh_UnlockModule,msg.moduleId)
end
function playerHandler.ResUnlockModuleListHandle(msg)
    if msg.state ~= 0 then return end
    local tb = {}
    for k,v in pairs(msg.moduleIds) do
        tb[v] = true
    end
    G.serverData["FuncUnlock"] = tb
end

function playerHandler.ReqCloseFunctionDataMessage()
    local m = ReqCloseFunctionDataMessage.New()
    sendReqMessage(m)
end
--[[

function playerHandler.updateRoleSkill()
    if G.serverData["roleInfo"] == nil then
        return;
    end

    G.serverData["roleSkill"] = {};
    local roleLevel = logicMgr.HeroManager.GetRoleInfo().level;
    local roleModleId = logicMgr.HeroManager.GetRoleInfo().leaderModelId;
    local roleCfg = G.dataTable["T_character"][roleModleId.."_"..roleLevel].f_skill;
    G.serverData["roleSkill"] = decodeJsonStrToTabel(roleCfg);
end
]]